package com.syni.mdd.yhd.common.all.aop;

import com.syni.mdd.sjb.common.component.utils.common.annotations.CheckParams;
import com.syni.mdd.sjb.common.component.utils.common.utils.RequestHeaderData;
import com.syni.mdd.sjb.common.component.utils.common.utils.ResultMapHelper;
import com.syni.mdd.sjb.common.component.utils.common.annotations.CheckParams;
import com.syni.mdd.yhd.common.all.constants.Constants;
import com.syni.mdd.yhd.common.all.constants.ResultCode;
import com.syni.mdd.yhd.common.all.entity.BmsDxClientRole;
import com.syni.mdd.yhd.common.all.entity.user.BmsUser;
import com.syni.mdd.yhd.common.all.service.BmsDxClientRoleService;
import com.syni.mdd.yhd.common.all.service.BmsVideoService;
import com.syni.mdd.yhd.common.all.utils.*;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * @className CheckParamsAspect
 * @description TOO
 * @Author cfx
 * @DATE 2019/4/25 17:23
 * @VERSION 1.0
 **/
@Aspect
@Order(2)
@Component
public class ControllerCheckParamsAspect {
    private final Logger log = LoggerFactory.getLogger(getClass());

    private static String TOKEN_CHECK = Constants.TOKEN_CHECK;

    @Autowired
    BmsDxClientRoleService bmsDxClientRoleService;

    @Around("@annotation(checkParams)")
    public Object around(ProceedingJoinPoint proceedingJoinPoint, CheckParams checkParams) throws Throwable {
        String[] params = checkParams.params();
        Map<String,Object> argsMap = new HashMap<>();
        Object[] args = proceedingJoinPoint.getArgs();
        log.info("检验参数（已转JSON）："+ GsonUtils.parseToJson(args));
        if(args.length > 0){
            for(Object arg : args){
                if(arg instanceof Map){
                    argsMap = (Map<String, Object>) arg;
                }
            }
        }
        RequestHeaderData requestHeaderData = new RequestHeaderData();
        //设置区分安卓/ios端
        int client = 1;
        if(requestHeaderData.containsKey("client")){
            client = requestHeaderData.getInteger("client");
        }
        argsMap.put("client",client);
        //设置区分商户/用户端
        int from = 1;
        if(requestHeaderData.containsKey("from")){
            from = requestHeaderData.getInteger("from");
        }
        argsMap.put("from",from);
        String userToken = requestHeaderData.getString("userid");
        argsMap.put("userIdentify",userToken);
        if(checkParams.checkAuth()){
            BmsUser bmsUser = null;
            //判断网关是否校验
            String token = requestHeaderData.getString("token");
            if(StringUtils.isBlank(token)){
                return ResultMapHelper.result(ResultCode.CODE_USER_TOKEN_FAIL,"token失效");
            }
            String USER_TOKEN_CHECK = requestHeaderData.getString("user_token_check");
            String CHECK = WebUtils.MD5(token + TOKEN_CHECK);
            if(CHECK.equals(USER_TOKEN_CHECK)) {
                log.info("zuul网关校验通过");
                if(StringUtils.isNotBlank(userToken)){
                    bmsUser = TokenManager.getUser(Integer.parseInt(userToken));
                }
            }else {
                if(requestHeaderData.containsKey("client")){
                    client = requestHeaderData.getInteger("client");
                    if(client == Constants.IOS_CLIENT || client == Constants.APP_CLIENT
                            || client == Constants.SMALL_PROGRAM || client == Constants.SMALL_ALI_CLIENT
                            || client == Constants.BUSINESS_MIN_APPP_CLIENT){
                        if(!(TokenUtils.checkToken(token,userToken) == TokenUtils.TOKEN_SUCCESS)){
                            log.info("校验失败");
                            return ResultMapHelper.result(ResultCode.CODE_USER_TOKEN_FAIL,"token失效");
                        }
                        userToken = TokenUtils.getUserThreadLocal().get().toString();
                    }else {
                        return ResultMapHelper.failure("client无法标识终端");
                    }
                }else {
                    //微信端（做兼容）
                    if(!argsMap.containsKey("open_id")){
                        return ResultMapHelper.failure("缺少参数open_id");
                    }
                    Integer userId = TokenManager.getUserId(argsMap.get("open_id").toString());
                    if(userId == null){
                        return ResultMapHelper.failure("用户不存在");
                    }
                    userToken = userId.toString();
                }
                bmsUser = TokenManager.getUser(Integer.parseInt(userToken));
                argsMap.put("userIdentify",userToken);
            }
            if (bmsUser == null) {
                return ResultMapHelper.result(ResultCode.CODE_USER_TOKEN_FAIL, "token失效");
            }
            //是否被冻结
            if(from == Constants.USER_CLIENT) {
                if (bmsUser.getIsFreeze() != null && bmsUser.getIsFreeze() == Constants.COMMON_FLAG_TRUE_INT) {
                    return ResultMapHelper.result(ResultCode.CODE_USER_TOKEN_FAIL, "账号已被冻结");
                }
            }else if(from == Constants.BUSINESS_CLIENT){
                if (bmsUser.getIsFreezeBus() != null && bmsUser.getIsFreezeBus() == Constants.COMMON_FLAG_TRUE_INT) {
                    return ResultMapHelper.result(ResultCode.CODE_USER_TOKEN_FAIL, "账号已被冻结");
                }
            }
        }
        if(requestHeaderData.containsKey("devid")) {
            argsMap.put("devId", requestHeaderData.getString("devid"));
        }
        if(params.length > 0){
            for(String param : params){
                String[] paramsRule = param.split(":");
                int startIndex = 0;
                for(int ii=0;ii< paramsRule.length;ii++) {
                    if(ii == startIndex) {
                        if (!argsMap.containsKey(paramsRule[ii])) {
                            return ResultMapHelper.failure(String.format("缺少参数%s", paramsRule[ii]));
                        }
                    }else {

                    }
                }
                //继续往下检验
            }
        }
        return proceedingJoinPoint.proceed(args);
    }
}
